package cn.zhaoyuening.zamh.manager;

import cn.zhaoyuening.zamh.handler.MsgHandler;
import cn.zhaoyuening.zamh.looper.MsgLooper;
import cn.zhaoyuening.zamh.msg.Msg;
import cn.zhaoyuening.zamh.queue.MsgQueue;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created by 赵岳宁 on 2017/6/3.
 */
public class BaseManager implements MsgManager {
    private Map<Integer,List<MsgHandler>> msgMap
            = new HashMap<Integer, List<MsgHandler>>();
    private MsgQueue queue;
    private MsgLooper looper;

    public BaseManager(final MsgQueue queue, final MsgLooper looper) {
        this.queue = queue;
        this.looper = looper;
        looper.setMsgMap(msgMap);
        looper.setQueue(queue);
        looper.loop();
    }


    public void addHandler(MsgHandler handler) {
        int msgId = handler.getMsgId();
        List<MsgHandler> handlers = msgMap.get(msgId);
        if (handlers==null){
            handlers = new LinkedList<MsgHandler>();
            msgMap.put(msgId, handlers);
        }
        handlers.add(handler);
    }

    public void sendMsg(Msg msg) {
        queue.pushMsg(msg);
        synchronized (queue) {
            queue.notify();
        }
    }
}
